//package com.lk.service;
//
//
//import java.nio.charset.StandardCharsets;
//import java.util.*;
//import java.util.concurrent.ConcurrentHashMap;
//
//import com.ghca.dbproxy.clean.BaseCleanService;
//import com.ghca.dbproxy.parsing.util.PolicyUtil;
//import com.ghca.dbproxy.util.ClientUtil;
//import com.ghca.dbproxy.util.PerformanceMonitorUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import com.ghca.dbproxy.clean.CleanService;
//import com.ghca.dbproxy.clean.CleanServiceFactory;
//import com.ghca.dbproxy.server.DBProxySession;
//
//import io.netty.buffer.ByteBuf;
//import io.netty.buffer.Unpooled;
//import io.netty.channel.Channel;
//import io.netty.channel.ChannelFuture;
//import io.netty.channel.ChannelFutureListener;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.ChannelInboundHandlerAdapter;
//import io.netty.channel.socket.SocketChannel;
//
//import static com.ghca.dbproxy.clean.BaseCleanService.sqlDownFlowCount;
//import static com.ghca.dbproxy.util.ClientUtil.getCurrentTimeMillis;
//
//@Slf4j
//public class DBProxyBackendHandler extends ChannelInboundHandlerAdapter {
//    private static final Logger logger = LoggerFactory.getLogger(DBProxyBackendHandler.class);
//    private static final String TIME_COMMING = "time_comming";
//
//    private final Channel inboundChannel;
//
//    private String remoteType;
//
//    private String clinetId;
//
//    public static TreeMap<Float, Object> sortedTotalTime = new TreeMap<>();
//
//    public DBProxyBackendHandler(Channel inboundChannel, String remoteType, String clinetId, ResponseMsg responseMsg) {
//        this.inboundChannel = inboundChannel;
//        this.remoteType = remoteType;
//        this.clinetId = clinetId;
//    }
//
//    @Override
//    public void channelActive(ChannelHandlerContext ctx) {
//        ctx.read();
//    }
//
//    @Override
//    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
//        sqlDownFlowCount(clinetId);
//        Integer downFlowBytesCount = (Integer) DBProxySession.getInstance().get(clinetId, "CILENT_DOWN_SQL_COUNT");
//        if (downFlowBytesCount == null) {
//            downFlowBytesCount = 0;
//        }
//        ((Map) DBProxySession.getInstance().get(clinetId, TIME_COMMING)).put("BackendchannelRead" + " " + downFlowBytesCount, ClientUtil.getCurrentTimeMillis());
//        ByteBuf buffer = (ByteBuf) msg;
//        byte[] bytes = new byte[buffer.readableBytes()];
//        buffer.readBytes(bytes);
//        buffer.release();
//        ((Map) DBProxySession.getInstance().get(clinetId, TIME_COMMING)).put("BackendreadBytes" + " " + downFlowBytesCount, ClientUtil.getCurrentTimeMillis());
//        ctx.channel();
//        String clinetIP = "192.168.2.229";
//        String hostName = "192.168.2.229";//写死以后，本地调试速度快很多
//        // 报文协议解析转换
//
//        Map<String, Object> parm = new HashMap<>();
//        parm.put("CLINET_IP", clinetIP);
//        parm.put("HOST_NAME", hostName);
//
//        CleanService cleanService = CleanServiceFactory.create(remoteType);
//        parm = new HashMap<>();
//        /**
//         * 全链路性能监控
//         * 节点4：从数据库接受请求
//         */
//        if (PerformanceMonitorUtil.enable) {
//            synchronized (PerformanceMonitorUtil.processRecordLock) {
//                if (DBProxySession.getInstance().get(clinetId, "PERFORMANCE_MONITOR_ISSYSTEMSQL") != null && !(boolean) DBProxySession.getInstance().get(clinetId, "PERFORMANCE_MONITOR_ISSYSTEMSQL")) {
//                    //不是系统sql
//                    PerformanceMonitorUtil.performanceMonitorRecord_resFromDB(clinetId, PerformanceMonitorUtil.now());
//                }
//            }
//        }
//        ((Map) DBProxySession.getInstance().get(clinetId, TIME_COMMING)).put("BackendbeforedoClean" + " " + downFlowBytesCount, ClientUtil.getCurrentTimeMillis());
//        byte[] newmsg = cleanService.doClean(bytes, clinetId, parm);
//
//
//        sendMessage(ctx, newmsg);
//    }
//
//    public void sendMessage(ChannelHandlerContext ctx, byte[] newmsg) {
//        if (remoteType.equalsIgnoreCase("ES")) {
//            int position = 0;
//            byte[] segMsg = new byte[2048];
//            if (newmsg.length > 0) {
//                for (int i = 0; i < newmsg.length; i++) {
//                    if (position < 2048 && i < newmsg.length) {
//                        segMsg[position] = newmsg[i];
//                        position++;
//                        if (position < 2048 && i != newmsg.length - 1) {
//                            continue;
//                        }
//                    }
//                    ByteBuf buf = Unpooled.wrappedBuffer(segMsg, 0, position);
//                    log.info(new String(buf.array(), StandardCharsets.UTF_8));
//                    inboundChannel.writeAndFlush(buf).addListener(new ChannelFutureListener() {
//                        @Override
//                        public void operationComplete(ChannelFuture future) {
//                            if (future.isSuccess()) {
//                                ctx.channel().read();
//                            } else {
//                                future.channel().close();
//                            }
//                        }
//                    });
//                    segMsg = new byte[2048];
//                    position = 0;
//                }
//            } else {
//                inboundChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
//                    @Override
//                    public void operationComplete(ChannelFuture future) {
//                        if (future.isSuccess()) {
//                            ctx.channel().read();
//                        } else {
//                            future.channel().close();
//                        }
//                    }
//                });
//            }
//        } else {
//            if (null == newmsg) {
//                newmsg = new byte[0];
//            }
//            ByteBuf buf = Unpooled.wrappedBuffer(newmsg);
//            ((Map) DBProxySession.getInstance().get(clinetId, TIME_COMMING)).put("downflowBeforeSend", getCurrentTimeMillis());
//            inboundChannel.writeAndFlush(buf).addListener(new ChannelFutureListener() {
//                @Override
//                public void operationComplete(ChannelFuture future) {
//                    perfLog();
//                    if (future.isSuccess()) {
//                        ctx.channel().read();
//                    } else {
//                        future.channel().close();
//                    }
//                }
//            });
//        }
//    }
//
//    TreeMap<Float, Object> timeMap = new TreeMap<>();
//
//    /**
//     * 性能日志打印
//     *
//     *
//     * @creator 李强
//     * @createTime 2023/10/30 16:28
//     *
//     * @modifier
//     * @modifyTime
//     * @modifyRemark
//     */
//    private void perfLog() {
//        if (ClientUtil.perfDebugLogStatic) {
//            ((Map) DBProxySession.getInstance().get(clinetId, TIME_COMMING)).put("downflowBeforeSend2", getCurrentTimeMillis());
//            LinkedHashMap<String, Long> timeComming1 = (LinkedHashMap<String, Long>) DBProxySession.getInstance().get(clinetId, TIME_COMMING);
//            Long a = null, b = null;
//            StringBuilder builder = new StringBuilder();
//            long oldValue = 0;
//
//            float BackendchannelRead0diff = 0;
//            for (Map.Entry<String, Long> time_comming : timeComming1.entrySet()) {
//                String key = time_comming.getKey();
//                Long value = time_comming.getValue();
//                if (oldValue == 0) oldValue = value;
//                float diff = ((float) (value - oldValue)) / 1000000;
//                if (diff < 0.001) {
//                    continue;
//                }
////				builder.append(key + " : " + value).append(" diff:" + diff).append("\n");
////				builder.append(key + " : " ).append(" diff:" + diff).append("\n");
//                if ("BackendchannelRead 0".equalsIgnoreCase(key)) {
//                    BackendchannelRead0diff = diff;
//                }
//                builder.append(key + " : ");
//                oldValue = value;
//                if (diff < 0.01) {
//                    continue;
//                }
//                if (a == null) a = value;
//                else b = value;
//                timeMap.put(diff, key);
//            }
//            timeMap.entrySet().forEach(entry -> {
//                System.out.println(entry.getValue() + " : " + entry.getKey());
//            });
//            timeMap.clear();
//            float total = ((float) (b - a)) / 1000000;
//            sortedTotalTime.put(total, timeComming1);
//            builder.append("total " + total + " ms").append(" \ncutBackendchannelRead0diff:").append(total - BackendchannelRead0diff).append("\n\n");
//            System.out.println(builder.toString());
//            DBProxySession.getInstance().put(clinetId, TIME_COMMING, new LinkedHashMap<>());
//        }
//    }
//
//    public static void printTotalList() {
//        for (Map.Entry<Float, Object> entry : sortedTotalTime.entrySet()) {
//            System.out.println("total " + entry.getKey() + " ms");
//        }
//        sortedTotalTime.clear();
//    }
//
//    @Override
//    public void channelInactive(ChannelHandlerContext ctx) {
//        DBProxyFrontendHandler.closeOnFlush(inboundChannel);
//    }
//
//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//        log.error(cause.getMessage());
//        DBProxyFrontendHandler.closeOnFlush(ctx.channel());
//    }
//
//    @Override
//    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        super.handlerRemoved(ctx);
//        BaseCleanService.sendDownFlowLog(clinetId);
//    }
//
//
//}
